<template>
  <div class="app-container">
    <div class="top">
      <div class="top-nav">
        <div>
          <i class="iconfont icon-a-canyurenshu_huaban1_huaban1"></i>
        </div>
        <div class="text">浏览次数</div>
        <div class="person">{{ participate }}</div>
      </div>
      <div class="top-nav dati">
        <div>
          <i class="iconfont icon-a-canyurenshu_huaban1_huaban1"></i>
        </div>
        <div class="text">答题人数</div>
        <div class="person">{{ answerCount }}</div>
      </div>
    </div>
    <el-divider></el-divider>
    <div class="mid-content">
      <div style="display: flex">
        <div class="title" style="flex: auto">调查问卷
        </div>

      </div>
      <div style="margin-top: 20px">
        <el-date-picker
          v-model="queryParams.times"
          type="date"
          placeholder="选择日期"
          style="margin-left: 30px"
          :picker-options="pickerOptions"
          @change="changeTime()"
        >
        </el-date-picker>
        <el-select  @change="getInfoByQuestionId" clearable v-model="queryParams.questionId"   placeholder="请选择题目" style="margin-left: 20px" >
          <el-option v-for="item in questionList" :label="item.content" :value="item.id" ></el-option>
        </el-select>
        <el-select v-model="queryParams.answer" clearable placeholder="请选择选项" style="margin-left: 20px">
          <el-option v-for="item in contentList" :label="item.content" :value="item.id" ></el-option>
        </el-select>
        <el-select @change="getPlotList" v-model="queryParams.region" clearable placeholder="请选择城市" style="margin-left: 20px">
          <el-option v-for="item in regionList" :label="item.regionName" :value="item.regionId" ></el-option>
        </el-select>

        <el-select  v-model="queryParams.plot" clearable placeholder="请选择小区" style="margin-left: 20px">
          <el-option v-for="item in plotList" :label="item.regionName" :value="item.regionId" ></el-option>
        </el-select>
<!--        <el-select v-model="queryParams.answer" clearable placeholder="请选择选项" style="margin-left: 20px">-->
<!--          <el-option v-for="item in contentList" :label="item.content" :value="item.id" ></el-option>-->
<!--        </el-select>-->
<!--        <el-cascader style="margin-left: 20px"-->
<!--          :value="queryParams.region"-->
<!--          :options="regionList"-->
<!--          :props="{label:'regionName', value:'regionId',children:'children',checkStrictly: true}"-->
<!--          clearable></el-cascader>-->
      </div>
      <div class="btn">
        <el-button type="success" size="mini" @click="exportUserTable"
        >用户统计导出</el-button>
        <el-button type="success" size="mini" @click="exportTable"
          >问卷统计导出</el-button>
        <el-radio-group v-model="isCollapse" border>
          <el-radio-button :label="false">列表</el-radio-button>
          <el-radio-button :label="true">明细</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <div
      class="first-question"
      v-for="(item, index) in statistics"
      :key="item.id"
    >
      <div class="question">
        <div class="text">第{{ index + 1 }}题:{{ item.content }}</div>
        <div v-show="isCollapse == false" class="table">
          <el-table :data="item.statisticsDtos" border style="width: 100%">
            <el-table-column prop="content" label="选项" width="180">
            </el-table-column>
            <el-table-column prop="count" label="小计" width="180">
            </el-table-column>
            <el-table-column prop="percentage" label="比例">
              <template slot-scope="scope">
                <el-progress
                  :text-inside="true"
                  :stroke-width="26"
                  :percentage="parseFloat(scope.row.percentage)"
                ></el-progress>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <pie-chart
          v-show="isCollapse"
          :id="`chart+${index}`"
          style="width: 300px; height: 300px"
          :chart-data="item.statisticsDtos"
          class="pie"
        ></pie-chart>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listUserAnswer,
  getUserAnswer,
  delUserAnswer,
  addUserAnswer,
  updateUserAnswer,
  tablestatistics,
  participateCount,
  exportStatistics,
  selectListQuestion,
  getInfoByQuestionId,
  getRegionTreeSelect,
  getRegionList,
  getPlotList
} from "@/api/question/userAnswer";
import * as echarts from "echarts";

import PieChart from "../../dashboard/PieChart.vue";
require("echarts/theme/macarons"); // echarts theme
export default {
  components: { PieChart },
  name: "UserAnswer",
  comments: {
    PieChart,
  },
  data() {
    return {
      isCollapse: false,
      tableData: [],
      chart: null,
      statistics: [],
      participate: "",
      answerCount: "",
      questionList:[],
      contentList:[],
      regionList:[],
      plotList:[],
      regionValue:'',
      param:{
        time:null,
      },
      queryParams: {
        pageNum: 1,
        times: null,
        region:null,
        questionId:null,
        answer:null,
        plot:null
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
    }
  },
  created() {},
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  mounted() {
    this.tablestatistics();
    this.participateCount();
    this.selectListQuestion();
    // this.getRegionTreeSelect()
    this.getRegionList()
  },
  methods: {

    selectListQuestion(){
      selectListQuestion().then(response => {
          this.questionList = response.data;
        }
      );
    },

    getInfoByQuestionId(value){
      if (value != null && value != ''){
        getInfoByQuestionId(value).then(response => {
            this.contentList = response.data;
          })
      }else {
        this.contentList = []
        this.queryParams.answer = ''
      }
    },

    getRegionList(){
      getRegionList().then(res =>{
        this.regionList =res.data
      })
    },

    getPlotList(value){
      if (value != null && value != ''){
      getPlotList(value).then(res =>{
        this.plotList =res.data
      })
    }else{
        this.plotList = []
        this.queryParams.plot = ''
        }
    },


    // getRegionTreeSelect(){
    //   getRegionTreeSelect().then(res =>{
    //     this.regionList =res.data
    //   })
    // },
    handleNodeClick(){
    },
    formattedDate(time){
      const date = new Date(time);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;
      console.log(formattedDate);
      return formattedDate;
    },
    changeTime(){
      this.tablestatistics()
    },
    exportTable() {
      this.download(
        "questionStatistics/exportStatistics",
        {
          time :""?"":this.formattedDate(this.queryParams.times),
          answer: this.queryParams.answer,
          region: this.queryParams.region,
          plot: this.queryParams.plot
        },
        `问卷调查统计.xlsx`
      );
    },

    exportUserTable(){
      this.download(
        "questionStatistics/exportUserStatistics",
        {
          time :""?"":this.formattedDate(this.queryParams.times),
          answer: this.queryParams.answer,
          region: this.queryParams.region,
          plot: this.queryParams.plot
        },
        `人员统计.xlsx`
      );
    },
    participateCount() {
      participateCount().then((res) => {
        this.participate = res.data.participateCount;
        this.answerCount = res.data.answerCount;
      });
    },

    tablestatistics() {
      tablestatistics({time:this.formattedDate(this.queryParams.times)}).then((res) => {
        this.statistics = res.data;
      });
    },
    initChart(ref) {
      console.log(ref);
      this.chart = echarts.init(document.getElementById("#graph0"), "macarons");
      let dom;
      // this.chart = echarts.init(this.$refs[ref],"macarons")
      this.chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          left: "center",
          bottom: "10",
          data: ["Industries", "Technology", "Forex", "Gold", "Forecasts"],
        },
        series: [
          {
            name: "WEEKLY WRITE ARTICLES",
            type: "pie",
            roseType: "radius",
            radius: [15, 95],
            center: ["50%", "38%"],
            data: [
              { value: 320, name: "Industries" },
              { value: 240, name: "Technology" },
              { value: 149, name: "Forex" },
              { value: 100, name: "Gold" },
              { value: 59, name: "Forecasts" },
            ],
            animationEasing: "cubicInOut",
            animationDuration: 2600,
          },
        ],
      });
    },

    /** 查询用户记录列表 */

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        questionId: null,
        questionContent: null,
        activityId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUserAnswer(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUserAnswer(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserAnswer(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除用户记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUserAnswer(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */

  },
};
</script>

<style>
.top {
  display: flex;
}
.top-nav {
  width: 500px;
  height: 50px;
  display: flex;
  background-color: rgb(63, 128, 240);
  margin-left: 100px;
  border-radius: 20px;
  color: white;
}
.dati {
  background-color: orange;
}
.top-nav div {
  margin-left: 30px;
  width: 100%;
  text-align: center;
  margin: auto 0;
  font-size: 30px;
}
.top-nav .iconfont {
  font-size: 30px;
}

/* 中间部分 */
.mid-content .title {
  text-align: center;
  color: black;
  font-size: 35px;
}
.first-question {
  margin-top: 30px;
  padding: 0 30px;
}

.mid-content .btn {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn .el-button {
  margin-right: 20px;
}

.first-question .table {
  margin-top: 20px;
}

.pie {
  margin: 0 auto;
  margin-top: 20px;
}
</style>
